//fcntl函数获得/设置文件状态标记
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
using namespace std;

void SetNonBlock(int fd)
{
    int f1 = fcntl(fd, F_GETFL); //获得文件状态标记
    if(f1<0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd,F_SETFL,f1|O_NONBLOCK);//设置文件状态标记 将其设置为非阻塞
}

static const int size = 1024;
int main()
{
    SetNonBlock(0);
    char buffer[size];
    while(true)
    {
        ssize_t n = read(0,buffer,sizeof(buffer)-1);
        buffer[n]= 0;
        if(n>0)
        {
            cout<<buffer<<endl;
        }
        else if(0 == n) 
        {
            cout<<"read done"<<endl;
            break;
        }
        else //1.read读取出错  2.底层资源未就绪
        {
            if(EWOULDBLOCK == errno) //EWOULDBLOCK == 11
            {
                cout<<"fd:0 data not ready  try again!"<<endl;
            }
            else
            {
                cout<<"read error, n = "<<n<<"error code:"<<errno<<"strerrno is:"<<strerror(errno)<<endl;
            }
        }
    }
    return 0;
}